package com.solairen.myapplication.Pager;

import static com.solairen.myapplication.data.ModelKt.RESULTS_KEY;
import static com.solairen.myapplication.data.ModelKt.SP_FILENAME;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.solairen.myapplication.MainActivity;
import com.solairen.myapplication.R;
import com.solairen.myapplication.SelfEvaluateActivity;
import com.solairen.myapplication.camera.CameraActivity;
import com.solairen.myapplication.data.DiaData;
import com.solairen.myapplication.data.MainVM;
import com.solairen.myapplication.net.BaseModel;
import com.solairen.myapplication.net.HttpResult;
import com.solairen.myapplication.utils.UtilsKt;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class DiagnoseResult extends AppCompatActivity {

    private TextView mSymptomTextView;
    private TextView mRankTextView;
    private Button ok;

    private MainVM mainVM;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.diagnose_result);
        mSymptomTextView = findViewById(R.id.tv_symptom);
//        mRankTextView = findViewById(R.id.tv_rank);
        ok = findViewById(R.id.OK);

        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DiagnoseResult.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        });

        SharedPreferences sp = getSharedPreferences(SP_FILENAME, MODE_PRIVATE);
        String analysisResult = sp.getString("analysis_result","没获取到hhh");
        mSymptomTextView.setText(analysisResult);

        // fixme 保存结果到历史
        String results = sp.getString(RESULTS_KEY, null);
        if (results == null) {
            ArrayList<DiaData> result = new ArrayList<>();
            DiaData diaData = new DiaData(analysisResult, "");
            result.add(diaData);
            sp.edit().putString(RESULTS_KEY, UtilsKt.toJsonString(result)).apply();
        } else {
            // 保存到list中
            List<DiaData> diaData = UtilsKt.toList(results, DiaData.class);
            DiaData data = new DiaData(analysisResult, "");
            diaData.add(data);
            sp.edit().putString(RESULTS_KEY, UtilsKt.toJsonString(diaData)).apply();
        }

//        new FetchServerData().execute();

//        mainVM = new ViewModelProvider(this).get(MainVM.class);
//        // 获取数据
//        mainVM.getData();
//        // 监听数据
//        mainVM.getDataLD().observe(this, baseModelHttpResult -> {
//            if (baseModelHttpResult instanceof HttpResult.Success) {
//                // 显示数据
//                String result = ((HttpResult.Success<BaseModel<String>>) baseModelHttpResult).getModel().getData();
//                DiaData data = UtilsKt.toModel(result, DiaData.class);
//                mSymptomTextView.setText(data.getSymptom());
//                mRankTextView.setText(data.getRank());
//            } else if (baseModelHttpResult instanceof HttpResult.Failure) {
//                Toast.makeText(this, "获取数据失败", Toast.LENGTH_SHORT).show();
//            } else {
//                Toast.makeText(this, "获取数据失败", Toast.LENGTH_SHORT).show();
//            }
//        });
    }

    private class FetchServerData extends AsyncTask<Void, Void, JSONObject> {

        @Override
        protected JSONObject doInBackground(Void... voids) {
            try {
                URL url = new URL("https://yourserver.com/api/analyze");//todo 这里塞入api链接
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "application/json; utf-8");
                connection.setDoOutput(true);

                String jsonInputString = "{\"key\":\"value\"}"; // JSON请求体
                try (OutputStream os = connection.getOutputStream()) {
                    byte[] input = jsonInputString.getBytes("utf-8");
                    os.write(input, 0, input.length);
                }

                int code = connection.getResponseCode();
                if (code == HttpURLConnection.HTTP_OK) {
                    try (BufferedReader br = new BufferedReader(
                            new InputStreamReader(connection.getInputStream(), "utf-8"))) {
                        StringBuilder response = new StringBuilder();
                        String responseLine = null;
                        while ((responseLine = br.readLine()) != null) {
                            response.append(responseLine.trim());
                        }
                        return new JSONObject(response.toString());
                    }
                } else {
                    Log.e("FetchServerData", "Failed : HTTP error code : " + code);
                }

            } catch (Exception e) {
                Log.e("FetchServerData", "Error: ", e);
            }


            return null;
        }

        @Override
        protected void onPostExecute(JSONObject jsonObject) {
            if (jsonObject != null) {
                try {
                    String symptom = jsonObject.getString("symptom");
                    String rank = jsonObject.getString("rank");

                    // 更新UI
                    runOnUiThread(() -> {
                        mSymptomTextView.setText(symptom);
//                        mRankTextView.setText(rank);
                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(DiagnoseResult.this, "获取数据失败", Toast.LENGTH_SHORT).show();
            }
        }
    }
}














